home *** CD-ROM | disk | FTP | other *** search
/ Turnbull China Bikeride / Turnbull China Bikeride - Disc 1.iso / ARGONET / PD / FILER / TARSRC.SPK / c / compress < prev    next >
Text File  |  1993-11-11  |  49KB  |  1,558 lines

  1. /* 
  2.  * Compress - data compression program 
  3.  */
  4. #define min(a,b)        ((a>b) ? b : a)
  5.  
  6. /*
  7.  * machine variants which require cc -Dmachine:  pdp11, z8000, pcxt
  8.  */
  9.  
  10. /*
  11.  * Set USERMEM to the maximum amount of physical user memory available
  12.  * in bytes.  USERMEM is used to determine the maximum BITS that can be used
  13.  * for compression.
  14.  *
  15.  * SACREDMEM is the amount of physical memory saved for others; compress
  16.  * will hog the rest.
  17.  */
  18. #ifndef SACREDMEM
  19. #define SACREDMEM       0
  20. #endif
  21.  
  22. #ifndef USERMEM
  23. # define USERMEM        433484  /* default user memory */
  24. #endif
  25.  
  26. #ifdef interdata                /* (Perkin-Elmer) */
  27. #define SIGNED_COMPARE_SLOW     /* signed compare is slower than unsigned */
  28. #endif
  29.  
  30. #ifdef pdp11
  31. # define BITS   12      /* max bits/code for 16-bit machine */
  32. # define NO_UCHAR       /* also if "unsigned char" functions as signed char */
  33. # undef USERMEM 
  34. #endif /* pdp11 */      /* don't forget to compile with -i */
  35.  
  36. #ifdef z8000
  37. # define BITS   12
  38. # undef vax             /* weird preprocessor */
  39. # undef USERMEM 
  40. #endif /* z8000 */
  41.  
  42. #ifdef pcxt
  43. # define BITS   12
  44. # undef USERMEM
  45. #endif /* pcxt */
  46.  
  47. #ifdef USERMEM
  48. # if USERMEM >= (433484+SACREDMEM)
  49. #  define PBITS 16
  50. # else
  51. #  if USERMEM >= (229600+SACREDMEM)
  52. #   define PBITS        15
  53. #  else
  54. #   if USERMEM >= (127536+SACREDMEM)
  55. #    define PBITS       14
  56. #   else
  57. #    if USERMEM >= (73464+SACREDMEM)
  58. #     define PBITS      13
  59. #    else
  60. #     define PBITS      12
  61. #    endif
  62. #   endif
  63. #  endif
  64. # endif
  65. # undef USERMEM
  66. #endif /* USERMEM */
  67.  
  68. #ifdef PBITS            /* Preferred BITS for this memory size */
  69. # ifndef BITS
  70. #  define BITS PBITS
  71. # endif /* BITS */
  72. #endif /* PBITS */
  73.  
  74. #if BITS == 16
  75. # define HSIZE  69001           /* 95% occupancy */
  76. #endif
  77. #if BITS == 15
  78. # define HSIZE  35023           /* 94% occupancy */
  79. #endif
  80. #if BITS == 14
  81. # define HSIZE  18013           /* 91% occupancy */
  82. #endif
  83. #if BITS == 13
  84. # define HSIZE  9001            /* 91% occupancy */
  85. #endif
  86. #if BITS <= 12
  87. # define HSIZE  5003            /* 80% occupancy */
  88. #endif
  89.  
  90. #ifdef M_XENIX                  /* Stupid compiler can't handle arrays with */
  91. # if BITS == 16                 /* more than 65535 bytes - so we fake it */
  92. #  define XENIX_16
  93. # else
  94. #  if BITS > 13                 /* Code only handles BITS = 12, 13, or 16 */
  95. #   define BITS 13
  96. #  endif
  97. # endif
  98. #endif
  99.  
  100. /*
  101.  * a code_int must be able to hold 2**BITS values of type int, and also -1
  102.  */
  103. #if BITS > 15
  104. typedef long int        code_int;
  105. #else
  106. typedef int             code_int;
  107. #endif
  108.  
  109. #ifdef SIGNED_COMPARE_SLOW
  110. typedef unsigned long int count_int;
  111. typedef unsigned short int count_short;
  112. #else
  113. typedef long int          count_int;
  114. #endif
  115.  
  116. #ifdef NO_UCHAR
  117.  typedef char   char_type;
  118. #else
  119.  typedef        unsigned char   char_type;
  120. #endif /* UCHAR */
  121. char_type magic_header[] = { "\037\235" };      /* 1F 9D */
  122.  
  123. /* Defines for third byte of header */
  124. #define BIT_MASK        0x1f
  125. #define BLOCK_MASK      0x80
  126. /* Masks 0x40 and 0x20 are free.  I think 0x20 should mean that there is
  127.    a fourth header byte (for expansion).
  128. */
  129. #define INIT_BITS 9                     /* initial number of bits/code */
  130.  
  131. /*
  132.  * compress.c - File compression ala IEEE Computer, June 1984.
  133.  *
  134.  * Authors:     Spencer W. Thomas       (decvax!harpo!utah-cs!utah-gr!thomas)
  135.  *              Jim McKie               (decvax!mcvax!jim)
  136.  *              Steve Davies            (decvax!vax135!petsd!peora!srd)
  137.  *              Ken Turkowski           (decvax!decwrl!turtlevax!ken)
  138.  *              James A. Woods          (decvax!ihnp4!ames!jaw)
  139.  *              Joe Orost               (decvax!vax135!petsd!joe)
  140.  *
  141.  * $Header: compress.c,v 4.0 85/07/30 12:50:00 joe Release $
  142.  * $Log:        compress.c,v $
  143.  * Revision 4.0  85/07/30  12:50:00  joe
  144.  * Removed ferror() calls in output routine on every output except first.
  145.  * Prepared for release to the world.
  146.  * 
  147.  * Revision 3.6  85/07/04  01:22:21  joe
  148.  * Remove much wasted storage by overlaying hash table with the tables
  149.  * used by decompress: tab_suffix[1<<BITS], stack[8000].  Updated USERMEM
  150.  * computations.  Fixed dump_tab() DEBUG routine.
  151.  *
  152.  * Revision 3.5  85/06/30  20:47:21  jaw
  153.  * Change hash function to use exclusive-or.  Rip out hash cache.  These
  154.  * speedups render the megamemory version defunct, for now.  Make decoder
  155.  * stack global.  Parts of the RCS trunks 2.7, 2.6, and 2.1 no longer apply.
  156.  *
  157.  * Revision 3.4  85/06/27  12:00:00  ken
  158.  * Get rid of all floating-point calculations by doing all compression ratio
  159.  * calculations in fixed point.
  160.  *
  161.  * Revision 3.3  85/06/24  21:53:24  joe
  162.  * Incorporate portability suggestion for M_XENIX.  Got rid of text on #else
  163.  * and #endif lines.  Cleaned up #ifdefs for vax and interdata.
  164.  *
  165.  * Revision 3.2  85/06/06  21:53:24  jaw
  166.  * Incorporate portability suggestions for Z8000, IBM PC/XT from mailing list.
  167.  * Default to "quiet" output (no compression statistics).
  168.  *
  169.  * Revision 3.1  85/05/12  18:56:13  jaw
  170.  * Integrate decompress() stack speedups (from early pointer mods by McKie).
  171.  * Repair multi-file USERMEM gaffe.  Unify 'force' flags to mimic semantics
  172.  * of SVR2 'pack'.  Streamline block-compress table clear logic.  Increase 
  173.  * output byte count by magic number size.
  174.  * 
  175.  * Revision 3.0   84/11/27  11:50:00  petsd!joe
  176.  * Set HSIZE depending on BITS.  Set BITS depending on USERMEM.  Unrolled
  177.  * loops in clear routines.  Added "-C" flag for 2.0 compatibility.  Used
  178.  * unsigned compares on Perkin-Elmer.  Fixed foreground check.
  179.  *
  180.  * Revision 2.7   84/11/16  19:35:39  ames!jaw
  181.  * Cache common hash codes based on input statistics; this improves
  182.  * performance for low-density raster images.  Pass on #ifdef bundle
  183.  * from Turkowski.
  184.  *
  185.  * Revision 2.6   84/11/05  19:18:21  ames!jaw
  186.  * Vary size of hash tables to reduce time for small files.
  187.  * Tune PDP-11 hash function.
  188.  *
  189.  * Revision 2.5   84/10/30  20:15:14  ames!jaw
  190.  * Junk chaining; replace with the simpler (and, on the VAX, faster)
  191.  * double hashing, discussed within.  Make block compression standard.
  192.  *
  193.  * Revision 2.4   84/10/16  11:11:11  ames!jaw
  194.  * Introduce adaptive reset for block compression, to boost the rate
  195.  * another several percent.  (See mailing list notes.)
  196.  *
  197.  * Revision 2.3   84/09/22  22:00:00  petsd!joe
  198.  * Implemented "-B" block compress.  Implemented REVERSE sorting of tab_next.
  199.  * Bug fix for last bits.  Changed fwrite to putchar loop everywhere.
  200.  *
  201.  * Revision 2.2   84/09/18  14:12:21  ames!jaw
  202.  * Fold in news changes, small machine typedef from thomas,
  203.  * #ifdef interdata from joe.
  204.  *
  205.  * Revision 2.1   84/09/10  12:34:56  ames!jaw
  206.  * Configured fast table lookup for 32-bit machines.
  207.  * This cuts user time in half for b <= FBITS, and is useful for news batching
  208.  * from VAX to PDP sites.  Also sped up decompress() [fwrite->putc] and
  209.  * added signal catcher [plus beef in writeerr()] to delete effluvia.
  210.  *
  211.  * Revision 2.0   84/08/28  22:00:00  petsd!joe
  212.  * Add check for foreground before prompting user.  Insert maxbits into
  213.  * compressed file.  Force file being uncompressed to end with ".Z".
  214.  * Added "-c" flag and "zcat".  Prepared for release.
  215.  *
  216.  * Revision 1.10  84/08/24  18:28:00  turtlevax!ken
  217.  * Will only compress regular files (no directories), added a magic number
  218.  * header (plus an undocumented -n flag to handle old files without headers),
  219.  * added -f flag to force overwriting of possibly existing destination file,
  220.  * otherwise the user is prompted for a response.  Will tack on a .Z to a
  221.  * filename if it doesn't have one when decompressing.  Will only replace
  222.  * file if it was compressed.
  223.  *
  224.  * Revision 1.9  84/08/16  17:28:00  turtlevax!ken
  225.  * Removed scanargs(), getopt(), added .Z extension and unlimited number of
  226.  * filenames to compress.  Flags may be clustered (-Ddvb12) or separated
  227.  * (-D -d -v -b 12), or combination thereof.  Modes and other status is
  228.  * copied with copystat().  -O bug for 4.2 seems to have disappeared with
  229.  * 1.8.
  230.  *
  231.  * Revision 1.8  84/08/09  23:15:00  joe
  232.  * Made it compatible with vax version, installed jim's fixes/enhancements
  233.  *
  234.  * Revision 1.6  84/08/01  22:08:00  joe
  235.  * Sped up algorithm significantly by sorting the compress chain.
  236.  *
  237.  * Revision 1.5  84/07/13  13:11:00  srd
  238.  * Added C version of vax asm routines.  Changed structure to arrays to
  239.  * save much memory.  Do unsigned compares where possible (faster on
  240.  * Perkin-Elmer)
  241.  *
  242.  * Revision 1.4  84/07/05  03:11:11  thomas
  243.  * Clean up the code a little and lint it.  (Lint complains about all
  244.  * the regs used in the asm, but I'm not going to "fix" this.)
  245.  *
  246.  * Revision 1.3  84/07/05  02:06:54  thomas
  247.  * Minor fixes.
  248.  *
  249.  * Revision 1.2  84/07/05  00:27:27  thomas
  250.  * Add variable bit length output.
  251.  *
  252.  */
  253. static char rcs_ident[] = "$Header: compress.c,v 4.0 85/07/30 12:50:00 joe Release $";
  254.  
  255. #include <stdio.h>
  256. #include <ctype.h>
  257. #include <signal.h>
  258.  
  259. #ifdef __riscos
  260. #include "kernel.h"
  261. #else
  262. #include <sys/types.h>
  263. #include <sys/stat.h>
  264. #endif
  265.  
  266. #define ARGVAL() (*++(*argv) || (--argc && *++argv))
  267.  
  268. int n_bits;                             /* number of bits/code */
  269. int maxbits = BITS;                     /* user settable max # bits/code */
  270. code_int maxcode;                       /* maximum code, given n_bits */
  271. code_int maxmaxcode = 1 << BITS;        /* should NEVER generate this code */
  272. #ifdef COMPATIBLE               /* But wrong! */
  273. # define MAXCODE(n_bits)        (1 << (n_bits) - 1)
  274. #else
  275. # define MAXCODE(n_bits)        ((1 << (n_bits)) - 1)
  276. #endif /* COMPATIBLE */
  277.  
  278. #ifdef XENIX_16
  279. count_int htab0[8192];
  280. count_int htab1[8192];
  281. count_int htab2[8192];
  282. count_int htab3[8192];
  283. count_int htab4[8192];
  284. count_int htab5[8192];
  285. count_int htab6[8192];
  286. count_int htab7[8192];
  287. count_int htab8[HSIZE-65536];
  288. count_int * htab[9] = {
  289.         htab0, htab1, htab2, htab3, htab4, htab5, htab6, htab7, htab8 };
  290.  
  291. #define htabof(i)       (htab[(i) >> 13][(i) & 0x1fff])
  292. unsigned short code0tab[16384];
  293. unsigned short code1tab[16384];
  294. unsigned short code2tab[16384];
  295. unsigned short code3tab[16384];
  296. unsigned short code4tab[16384];
  297. unsigned short * codetab[5] = {
  298.         code0tab, code1tab, code2tab, code3tab, code4tab };
  299.  
  300. #define codetabof(i)    (codetab[(i) >> 14][(i) & 0x3fff])
  301.  
  302. #else   /* Normal machine */
  303. count_int htab [HSIZE];
  304. unsigned short codetab [HSIZE];
  305. #define htabof(i)       htab[i]
  306. #define codetabof(i)    codetab[i]
  307. #endif  /* XENIX_16 */
  308. code_int hsize = HSIZE;                 /* for dynamic table sizing */
  309. count_int fsize;
  310.  
  311. /*
  312.  * To save much memory, we overlay the table used by compress() with those
  313.  * used by decompress().  The tab_prefix table is the same size and type
  314.  * as the codetab.  The tab_suffix table needs 2**BITS characters.  We
  315.  * get this from the beginning of htab.  The output stack uses the rest
  316.  * of htab, and contains characters.  There is plenty of room for any
  317.  * possible stack (stack used to be 8000 characters).
  318.  */
  319.  
  320. #define tab_prefixof(i) codetabof(i)
  321. #ifdef XENIX_16
  322. # define tab_suffixof(i)        ((char_type *)htab[(i)>>15])[(i) & 0x7fff]
  323. # define de_stack               ((char_type *)(htab2))
  324. #else   /* Normal machine */
  325. # define tab_suffixof(i)        ((char_type *)(htab))[i]
  326. # define de_stack               ((char_type *)&tab_suffixof(1<<BITS))
  327. #endif  /* XENIX_16 */
  328.  
  329. code_int free_ent = 0;                  /* first unused entry */
  330. int exit_stat = 0;
  331.  
  332. code_int getcode();
  333.  
  334. Usage() {
  335. #ifdef DEBUG
  336. fprintf(stderr,"Usage: compress [-dDVfc] [-b maxbits] [file ...]\n");
  337. }
  338. int debug = 0;
  339. #else
  340. fprintf(stderr,"Usage: compress [-dfvcV] [-b maxbits] [file ...]\n");
  341. }
  342. #endif /* DEBUG */
  343. int nomagic = 0;        /* Use a 3-byte magic number header, unless old file */
  344. int zcat_flg = 0;       /* Write output on stdout, suppress messages */
  345. int quiet = 1;          /* don't tell me about compression */
  346.  
  347. /*
  348.  * block compression parameters -- after all codes are used up,
  349.  * and compression rate changes, start over.
  350.  */
  351. int block_compress = BLOCK_MASK;
  352. int clear_flg = 0;
  353. long int ratio = 0;
  354. #define CHECK_GAP 10000 /* ratio check interval */
  355. count_int checkpoint = CHECK_GAP;
  356. /*
  357.  * the next two codes should not be changed lightly, as they must not
  358.  * lie within the contiguous general code space.
  359.  */ 
  360. #define FIRST   257     /* first free entry */
  361. #define CLEAR   256     /* table clear output code */
  362.  
  363. int force = 0;
  364. char ofname [100];
  365. #ifdef DEBUG
  366. int verbose = 0;
  367. #endif /* DEBUG */
  368. int (*bgnd_flag)();
  369.  
  370. int do_decomp = 0;
  371.  
  372. /*****************************************************************
  373.  * TAG( main )
  374.  *
  375.  * Algorithm from "A Technique for High Performance Data Compression",
  376.  * Terry A. Welch, IEEE Computer Vol 17, No 6 (June 1984), pp 8-19.
  377.  *
  378.  * Usage: compress [-dfvc] [-b bits] [file ...]
  379.  * Inputs:
  380.  *      -d:         If given, decompression is done instead.
  381.  *
  382.  *      -c:         Write output on stdout, don't remove original.
  383.  *
  384.  *      -b:         Parameter limits the max number of bits/code.
  385.  *
  386.  *      -f:         Forces output file to be generated, even if one already
  387.  *                  exists, and even if no space is saved by compressing.
  388.  *                  If -f is not used, the user will be prompted if stdin is
  389.  *                  a tty, otherwise, the output file will not be overwritten.
  390.  *
  391.  *      -v:         Write compression statistics
  392.  *
  393.  *      file ...:   Files to be compressed.  If none specified, stdin
  394.  *                  is used.
  395.  * Outputs:
  396.  *      file.Z:     Compressed form of file with same mode, owner, and utimes
  397.  *      or stdout   (if stdin used as input)
  398.  *
  399.  * Assumptions:
  400.  *      When filenames are given, replaces with the compressed version
  401.  *      (.Z suffix) only if the file decreases in size.
  402.  * Algorithm:
  403.  *      Modified Lempel-Ziv method (LZW).  Basically finds common
  404.  * substrings and replaces them with a variable size code.  This is
  405.  * deterministic, and can be done on the fly.  Thus, the decompression
  406.  * procedure needs no input table, but tracks the way the table was built.
  407.  */
  408.  
  409. #ifdef __riscos
  410. #include "stat.h"
  411. #define unlink remove
  412. #endif
  413.  
  414. main( argc, argv )
  415. register int argc; char **argv;
  416. {
  417.     int overwrite = 0;  /* Do not overwrite unless given -f flag */
  418.     char tempname[100];
  419.     char **filelist, **fileptr;
  420.     char *cp, *rindex(), *malloc();
  421.     struct stat statbuf;
  422.     extern onintr(), oops();
  423.  
  424.  
  425.     if ( (bgnd_flag = signal ( SIGINT, SIG_IGN )) != SIG_IGN ) {
  426.         signal ( SIGINT, onintr );
  427.         signal ( SIGSEGV, oops );
  428.     }
  429.  
  430. #ifdef COMPATIBLE
  431.     nomagic = 1;        /* Original didn't have a magic number */
  432. #endif /* COMPATIBLE */
  433.  
  434.     filelist = fileptr = (char **)(malloc(argc * sizeof(*argv)));
  435.     *filelist = NULL;
  436.  
  437.     if((cp = rindex(argv[0], '/')) != 0) {
  438.         cp++;
  439.     } else {
  440.         cp = argv[0];
  441.     }
  442.     if(strcmp(cp, "uncompress") == 0) {
  443.         do_decomp = 1;
  444.     } else if(strcmp(cp, "zcat") == 0) {
  445.         do_decomp = 1;
  446.         zcat_flg = 1;
  447.     }
  448.  
  449. #ifdef BSD4_2
  450.     /* 4.2BSD dependent - take it out if not */
  451.     setlinebuf( stderr );
  452. #endif /* BSD4_2 */
  453.  
  454.     /* Argument Processing
  455.      * All flags are optional.
  456.      * -D => debug
  457.      * -V => print Version; debug verbose
  458.      * -d => do_decomp
  459.      * -v => unquiet
  460.      * -f => force overwrite of output file
  461.      * -n => no header: useful to uncompress old files
  462.      * -b maxbits => maxbits.  If -b is specified, then maxbits MUST be
  463.      *      given also.
  464.      * -c => cat all output to stdout
  465.      * -C => generate output compatible with compress 2.0.
  466.      * if a string is left, must be an input filename.
  467.      */
  468.     for (argc--, argv++; argc > 0; argc--, argv++) {
  469.         if (**argv == '-') {    /* A flag argument */
  470.             while (*++(*argv)) {        /* Process all flags in this arg */
  471.                 switch (**argv) {
  472. #ifdef DEBUG
  473.                     case 'D':
  474.                         debug = 1;
  475.                         break;
  476.                     case 'V':
  477.                         verbose = 1;
  478.                         version();
  479.                         break;
  480. #else
  481.                     case 'V':
  482.                         version();
  483.                         break;
  484. #endif /* DEBUG */
  485.                     case 'v':
  486.                         quiet = 0;
  487.                         break;
  488.                     case 'd':
  489.                         do_decomp = 1;
  490.                         break;
  491.                     case 'f':
  492.                     case 'F':
  493.                         overwrite = 1;
  494.                         force = 1;
  495.                         break;
  496.                     case 'n':
  497.                         nomagic = 1;
  498.                         break;
  499.                     case 'C':
  500.                         block_compress = 0;
  501.                         break;
  502.                     case 'b':
  503.                         if (!ARGVAL()) {
  504.                             fprintf(stderr, "Missing maxbits\n");
  505.                             Usage();
  506.                             exit(1);
  507.                         }
  508.                         maxbits = atoi(*argv);
  509.                         goto nextarg;
  510.                     case 'c':
  511.                         zcat_flg = 1;
  512.                         break;
  513.                     case 'q':
  514.                         quiet = 1;
  515.                         break;
  516.                     default:
  517.                         fprintf(stderr, "Unknown flag: '%c'; ", **argv);
  518.                         Usage();
  519.                         exit(1);
  520.                 }
  521.             }
  522.         }
  523.         else {          /* Input file name */
  524.             *fileptr++ = *argv; /* Build input file list */
  525.             *fileptr = NULL;
  526.             /* process nextarg; */
  527.         }
  528.         nextarg: continue;
  529.     }
  530.  
  531.     if(maxbits < INIT_BITS) maxbits = INIT_BITS;
  532.     if (maxbits > BITS) maxbits = BITS;
  533.     maxmaxcode = 1 << maxbits;
  534.  
  535.     if (*filelist != NULL) {
  536.         for (fileptr = filelist; *fileptr; fileptr++) {
  537.             exit_stat = 0;
  538.             if (do_decomp != 0) {                       /* DECOMPRESSION */
  539.                 /* Check for .Z suffix */
  540.                 if (strcmp(*fileptr + strlen(*fileptr) - 2, "/Z") != 0) {
  541.                     /* No .Z: tack one on */
  542.                     strcpy(tempname, *fileptr);
  543.                     strcat(tempname, "/Z");
  544.                     *fileptr = tempname;
  545.                 }
  546.                 /* Open input file */
  547.                 if ((freopen(*fileptr, "r", stdin)) == NULL) {
  548.                         fprintf(stderr, "unable to open %s\n",*fileptr);
  549.                         continue;
  550.                 }
  551.                 /* Check the magic number */
  552.                 if (nomagic == 0) {
  553.                     if ((getchar() != (magic_header[0] & 0xFF))
  554.                      || (getchar() != (magic_header[1] & 0xFF))) {
  555.                         fprintf(stderr, "%s: not in compressed format\n",
  556.                             *fileptr);
  557.                         continue;
  558.                     }
  559.                     maxbits = getchar();        /* set -b from file */
  560.                     block_compress = maxbits & BLOCK_MASK;
  561.                     maxbits &= BIT_MASK;
  562.                     maxmaxcode = 1 << maxbits;
  563.                     if(maxbits > BITS) {
  564.                         fprintf(stderr,
  565.                         "%s: compressed with %d bits, can only handle %d bits\n",
  566.                         *fileptr, maxbits, BITS);
  567.                         continue;
  568.                     }
  569.                 }
  570.                 /* Generate output filename */
  571.                 strcpy(ofname, *fileptr);
  572.                 ofname[strlen(*fileptr) - 2] = '\0';  /* Strip off .Z */
  573.             } else {                                    /* COMPRESSION */
  574.                 if (strcmp(*fileptr + strlen(*fileptr) - 2, "/Z") == 0) {
  575.                         fprintf(stderr, "%s: already has /Z suffix -- no change\n",
  576.                             *fileptr);
  577.                     continue;
  578.                 }
  579.                 /* Open input file */
  580.                 if ((freopen(*fileptr, "r", stdin)) == NULL) {
  581.                     fprintf(stderr, "unable to open %s\n", *fileptr); continue;
  582.                 }
  583.                 stat ( *fileptr, &statbuf );
  584.                 fsize = (long) statbuf.st_size;
  585.                 /*
  586.                  * tune hash table size for small files -- ad hoc,
  587.                  * but the sizes match earlier #defines, which
  588.                  * serve as upper bounds on the number of output codes. 
  589.                  */
  590.                 hsize = HSIZE;
  591.                 if ( fsize < (1 << 12) )
  592.                     hsize = min ( 5003, HSIZE );
  593.                 else if ( fsize < (1 << 13) )
  594.                     hsize = min ( 9001, HSIZE );
  595.                 else if ( fsize < (1 << 14) )
  596.                     hsize = min ( 18013, HSIZE );
  597.                 else if ( fsize < (1 << 15) )
  598.                     hsize = min ( 35023, HSIZE );
  599.                 else if ( fsize < 47000 )
  600.                     hsize = min ( 50021, HSIZE );
  601.  
  602.                 /* Generate output filename */
  603.                 strcpy(ofname, *fileptr);
  604. #ifndef BSD4_2          /* Short filenames */
  605. #ifdef __riscos
  606.                 if ((cp=rindex(ofname,'.')) != NULL)    cp++;
  607. #else
  608.                 if ((cp=rindex(ofname,'/')) != NULL)    cp++;
  609. #endif
  610.                 else                                    cp = ofname;
  611. #ifdef __riscos
  612.                 if (strlen(cp) > 8) {
  613. #else
  614.                 if (strlen(cp) > 12) {
  615. #endif
  616.                     fprintf(stderr,"%s: filename too long to tack on /Z\n",cp);
  617.                     continue;
  618.                 }
  619. #endif  /* BSD4_2               Long filenames allowed */
  620.                 strcat(ofname, "/Z");
  621.             }
  622.             /* Check for overwrite of existing file */
  623.             if (overwrite == 0 && zcat_flg == 0) {
  624.                 if (stat(ofname, &statbuf) == 0) {
  625.                     char response[2];
  626.                     response[0] = 'n';
  627.                     fprintf(stderr, "%s already exists;", ofname);
  628.                     if (foreground()) {
  629.                         fprintf(stderr, " do you wish to overwrite %s (y or n)? ",
  630.                         ofname);
  631.                         fflush(stderr);
  632. #ifdef __riscos
  633.                         do {
  634.                           response[0] = tolower(_kernel_osrdch());
  635.                         } while (response[0] != 'y' && response[0] != 'n');
  636.                         fprintf(stderr,"%c\n",response[0]);
  637. #else
  638.                         read(2, response, 2);
  639.                         while (response[1] != '\n') {
  640.                             if (read(2, response+1, 1) < 0) {   /* Ack! */
  641.                                 perror("stderr"); break;
  642.                             }
  643.                         }
  644. #endif
  645.                     }
  646.                     if (response[0] != 'y') {
  647.                         fprintf(stderr, "\tnot overwritten\n");
  648.                         continue;
  649.                     }
  650.                 }
  651.             }
  652.             if(zcat_flg == 0) {         /* Open output file */
  653.                 if (freopen(ofname, "w", stdout) == NULL) {
  654.                     fprintf(stderr, "unable to open %s\n", ofname);
  655.                     continue;
  656.                 }
  657.                 if(!quiet)
  658.                         fprintf(stderr, "%s: ", *fileptr);
  659.             }
  660.  
  661.             /* Actually do the compression/decompression */
  662.             if (do_decomp == 0) compress();
  663. #ifndef DEBUG
  664.             else                        decompress();
  665. #else
  666.             else if (debug == 0)        decompress();
  667.             else                        printcodes();
  668.             if (verbose)                dump_tab();
  669. #endif /* DEBUG */
  670.             if(zcat_flg == 0) {
  671.                 copystat(*fileptr, ofname);     /* Copy stats */
  672.                 if((exit_stat == 1) || (!quiet))
  673.                         putc('\n', stderr);
  674.             }
  675.         }
  676.     } else {            /* Standard input */
  677.         if (do_decomp == 0) {
  678.                 compress();
  679. #ifdef DEBUG
  680.                 if(verbose)             dump_tab();
  681. #endif /* DEBUG */
  682.                 if(!quiet)
  683.                         putc('\n', stderr);
  684.         } else {
  685.             /* Check the magic number */
  686.             if (nomagic == 0) {
  687.                 if ((getchar()!=(magic_header[0] & 0xFF))
  688.                  || (getchar()!=(magic_header[1] & 0xFF))) {
  689.                     fprintf(stderr, "stdin: not in compressed format\n");
  690.                     exit(1);
  691.                 }
  692.                 maxbits = getchar();    /* set -b from file */
  693.                 block_compress = maxbits & BLOCK_MASK;
  694.                 maxbits &= BIT_MASK;
  695.                 maxmaxcode = 1 << maxbits;
  696.                 fsize = 100000;         /* assume stdin large for USERMEM */
  697.                 if(maxbits > BITS) {
  698.                         fprintf(stderr,
  699.                         "stdin: compressed with %d bits, can only handle %d bits\n",
  700.                         maxbits, BITS);
  701.                         exit(1);
  702.                 }
  703.             }
  704. #ifndef DEBUG
  705.             decompress();
  706. #else
  707.             if (debug == 0)     decompress();
  708.             else                printcodes();
  709.             if (verbose)        dump_tab();
  710. #endif /* DEBUG */
  711.         }
  712.     }
  713.     exit(exit_stat);
  714. }
  715.  
  716. static int offset;
  717. long int in_count = 1;                  /* length of input */
  718. long int bytes_out;                     /* length of compressed output */
  719. long int out_count = 0;                 /* # of codes output (for debugging) */
  720.  
  721. /*
  722.  * compress stdin to stdout
  723.  *
  724.  * Algorithm:  use open addressing double hashing (no chaining) on the 
  725.  * prefix code / next character combination.  We do a variant of Knuth's
  726.  * algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
  727.  * secondary probe.  Here, the modular division first probe is gives way
  728.  * to a faster exclusive-or manipulation.  Also do block compression with
  729.  * an adaptive reset, whereby the code table is cleared when the compression
  730.  * ratio decreases, but after the table fills.  The variable-length output
  731.  * codes are re-sized at this point, and a special CLEAR code is generated
  732.  * for the decompressor.  Late addition:  construct the table according to
  733.  * file size for noticeable speed improvement on small files.  Please direct
  734.  * questions about this implementation to ames!jaw.
  735.  */
  736.  
  737. compress() {
  738.     register long fcode;
  739.     register code_int i = 0;
  740.     register int c;
  741.     register code_int ent;
  742. #ifdef XENIX_16
  743.     register code_int disp;
  744. #else   /* Normal machine */
  745.     register int disp;
  746. #endif
  747.     register code_int hsize_reg;
  748.     register int hshift;
  749.  
  750. #ifndef COMPATIBLE
  751.     if (nomagic == 0) {
  752.         putchar(magic_header[0]); putchar(magic_header[1]);
  753.         putchar((char)(maxbits | block_compress));
  754.         if(ferror(stdout))
  755.                 writeerr();
  756.     }
  757. #endif /* COMPATIBLE */
  758.  
  759.     offset = 0;
  760.     bytes_out = 3;              /* includes 3-byte header mojo */
  761.     out_count = 0;
  762.     clear_flg = 0;
  763.     ratio = 0;
  764.     in_count = 1;
  765.     checkpoint = CHECK_GAP;
  766.     maxcode = MAXCODE(n_bits = INIT_BITS);
  767.     free_ent = ((block_compress) ? FIRST : 256 );
  768.  
  769.     ent = getchar ();
  770.  
  771.     hshift = 0;
  772.     for ( fcode = (long) hsize;  fcode < 65536L; fcode *= 2L )
  773.         hshift++;
  774.     hshift = 8 - hshift;                /* set hash code range bound */
  775.  
  776.     hsize_reg = hsize;
  777.     cl_hash( (count_int) hsize_reg);            /* clear hash table */
  778.  
  779. #ifdef SIGNED_COMPARE_SLOW
  780.     while ( (c = getchar()) != (unsigned) EOF ) {
  781. #else
  782.     while ( (c = getchar()) != EOF ) {
  783. #endif
  784.         in_count++;
  785.         fcode = (long) (((long) c << maxbits) + ent);
  786.         i = ((c << hshift) ^ ent);      /* xor hashing */
  787.  
  788.         if ( htabof (i) == fcode ) {
  789.             ent = codetabof (i);
  790.             continue;
  791.         } else if ( (long)htabof (i) < 0 )      /* empty slot */
  792.             goto nomatch;
  793.         disp = hsize_reg - i;           /* secondary hash (after G. Knott) */
  794.         if ( i == 0 )
  795.             disp = 1;
  796. probe:
  797.         if ( (i -= disp) < 0 )
  798.             i += hsize_reg;
  799.  
  800.         if ( htabof (i) == fcode ) {
  801.             ent = codetabof (i);
  802.             continue;
  803.         }
  804.         if ( (long)htabof (i) > 0 ) 
  805.             goto probe;
  806. nomatch:
  807.         output ( (code_int) ent );
  808.         out_count++;
  809.         ent = c;
  810. #ifdef SIGNED_COMPARE_SLOW
  811.         if ( (unsigned) free_ent < (unsigned) maxmaxcode) {
  812. #else
  813.         if ( free_ent < maxmaxcode ) {
  814. #endif
  815.             codetabof (i) = free_ent++; /* code -> hashtable */
  816.             htabof (i) = fcode;
  817.         }
  818.         else if ( (count_int)in_count >= checkpoint && block_compress )
  819.             cl_block ();
  820.     }
  821.     /*
  822.      * Put out the final code.
  823.      */
  824.     output( (code_int)ent );
  825.     out_count++;
  826.     output( (code_int)-1 );
  827.  
  828.     /*
  829.      * Print out stats on stderr
  830.      */
  831.     if(zcat_flg == 0 && !quiet) {
  832. #ifdef DEBUG
  833.         fprintf( stderr,
  834.                 "%ld chars in, %ld codes (%ld bytes) out, compression factor: ",
  835.                 in_count, out_count, bytes_out );
  836.         prratio( stderr, in_count, bytes_out );
  837.         fprintf( stderr, "\n");
  838.         fprintf( stderr, "\tCompression as in compact: " );
  839.         prratio( stderr, in_count-bytes_out, in_count );
  840.         fprintf( stderr, "\n");
  841.         fprintf( stderr, "\tLargest code (of last block) was %d (%d bits)\n",
  842.                 free_ent - 1, n_bits );
  843. #else /* !DEBUG */
  844.         fprintf( stderr, "Compression: " );
  845.         prratio( stderr, in_count-bytes_out, in_count );
  846. #endif /* DEBUG */
  847.     }
  848.     if(bytes_out > in_count)    /* exit(2) if no savings */
  849.         exit_stat = 2;
  850.     return;
  851. }
  852.  
  853. /*****************************************************************
  854.  * TAG( output )
  855.  *
  856.  * Output the given code.
  857.  * Inputs:
  858.  *      code:   A n_bits-bit integer.  If == -1, then EOF.  This assumes
  859.  *              that n_bits =< (long)wordsize - 1.
  860.  * Outputs:
  861.  *      Outputs code to the file.
  862.  * Assumptions:
  863.  *      Chars are 8 bits long.
  864.  * Algorithm:
  865.  *      Maintain a BITS character long buffer (so that 8 codes will
  866.  * fit in it exactly).  Use the VAX insv instruction to insert each
  867.  * code in turn.  When the buffer fills up empty it and start over.
  868.  */
  869.  
  870. static char buf[BITS];
  871.  
  872. #ifndef vax
  873. char_type lmask[9] = {0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80, 0x00};
  874. char_type rmask[9] = {0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff};
  875. #endif /* vax */
  876.  
  877. output( code )
  878. code_int  code;
  879. {
  880. #ifdef DEBUG
  881.     static int col = 0;
  882. #endif /* DEBUG */
  883.  
  884.     /*
  885.      * On the VAX, it is important to have the register declarations
  886.      * in exactly the order given, or the asm will break.
  887.      */
  888.     register int r_off = offset, bits= n_bits;
  889.     register char * bp = buf;
  890.  
  891. #ifdef DEBUG
  892.         if ( verbose )
  893.             fprintf( stderr, "%5d%c", code,
  894.                     (col+=6) >= 74 ? (col = 0, '\n') : ' ' );
  895. #endif /* DEBUG */
  896.     if ( code >= 0 ) {
  897. #ifdef vax
  898.         /* VAX DEPENDENT!! Implementation on other machines is below.
  899.          *
  900.          * Translation: Insert BITS bits from the argument starting at
  901.          * offset bits from the beginning of buf.
  902.          */
  903.         0;      /* Work around for pcc -O bug with asm and if stmt */
  904.         asm( "insv      4(ap),r11,r10,(r9)" );
  905. #else /* not a vax */
  906. /* 
  907.  * byte/bit numbering on the VAX is simulated by the following code
  908.  */
  909.         /*
  910.          * Get to the first byte.
  911.          */
  912.         bp += (r_off >> 3);
  913.         r_off &= 7;
  914.         /*
  915.          * Since code is always >= 8 bits, only need to mask the first
  916.          * hunk on the left.
  917.          */
  918.         *bp = (*bp & rmask[r_off]) | (code << r_off) & lmask[r_off];
  919.         bp++;
  920.         bits -= (8 - r_off);
  921.         code >>= 8 - r_off;
  922.         /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
  923.         if ( bits >= 8 ) {
  924.             *bp++ = code;
  925.             code >>= 8;
  926.             bits -= 8;
  927.         }
  928.         /* Last bits. */
  929.         if(bits)
  930.             *bp = code;
  931. #endif /* vax */
  932.         offset += n_bits;
  933.         if ( offset == (n_bits << 3) ) {
  934.             bp = buf;
  935.             bits = n_bits;
  936.             bytes_out += bits;
  937.             do
  938.                 putchar(*bp++);
  939.             while(--bits);
  940.             offset = 0;
  941.         }
  942.  
  943.         /*
  944.          * If the next entry is going to be too big for the code size,
  945.          * then increase it, if possible.
  946.          */
  947.         if ( free_ent > maxcode || (clear_flg > 0))
  948.         {
  949.             /*
  950.              * Write the whole buffer, because the input side won't
  951.              * discover the size increase until after it has read it.
  952.              */
  953.             if ( offset > 0 ) {
  954.                 if( fwrite( buf, 1, n_bits, stdout ) != n_bits)
  955.                         writeerr();
  956.                 bytes_out += n_bits;
  957.             }
  958.             offset = 0;
  959.  
  960.             if ( clear_flg ) {
  961.                 maxcode = MAXCODE (n_bits = INIT_BITS);
  962.                 clear_flg = 0;
  963.             }
  964.             else {
  965.                 n_bits++;
  966.                 if ( n_bits == maxbits )
  967.                     maxcode = maxmaxcode;
  968.                 else
  969.                     maxcode = MAXCODE(n_bits);
  970.             }
  971. #ifdef DEBUG
  972.             if ( debug ) {
  973.                 fprintf( stderr, "\nChange to %d bits\n", n_bits );
  974.                 col = 0;
  975.             }
  976. #endif /* DEBUG */
  977.         }
  978.     } else {
  979.         /*
  980.          * At EOF, write the rest of the buffer.
  981.          */
  982.         if ( offset > 0 )
  983.             fwrite( buf, 1, (offset + 7) / 8, stdout );
  984.         bytes_out += (offset + 7) / 8;
  985.         offset = 0;
  986.         fflush( stdout );
  987. #ifdef DEBUG
  988.         if ( verbose )
  989.             fprintf( stderr, "\n" );
  990. #endif /* DEBUG */
  991.         if( ferror( stdout ) )
  992.                 writeerr();
  993.     }
  994. }
  995.  
  996. /*
  997.  * Decompress stdin to stdout.  This routine adapts to the codes in the
  998.  * file building the "string" table on-the-fly; requiring no table to
  999.  * be stored in the compressed file.  The tables used herein are shared
  1000.  * with those of the compress() routine.  See the definitions above.
  1001.  */
  1002.  
  1003. decompress() {
  1004.     register char_type *stackp;
  1005.     register int finchar;
  1006.     register code_int code, oldcode, incode;
  1007.  
  1008.     /*
  1009.      * As above, initialize the first 256 entries in the table.
  1010.      */
  1011.     maxcode = MAXCODE(n_bits = INIT_BITS);
  1012.     for ( code = 255; code >= 0; code-- ) {
  1013.         tab_prefixof(code) = 0;
  1014.         tab_suffixof(code) = (char_type)code;
  1015.     }
  1016.     free_ent = ((block_compress) ? FIRST : 256 );
  1017.  
  1018.     finchar = oldcode = getcode();
  1019.     if(oldcode == -1)   /* EOF already? */
  1020.         return;                 /* Get out of here */
  1021.     putchar( (char)finchar );           /* first code must be 8 bits = char */
  1022.     if(ferror(stdout))          /* Crash if can't write */
  1023.         writeerr();
  1024.     stackp = de_stack;
  1025.  
  1026.     while ( (code = getcode()) > -1 ) {
  1027.  
  1028.         if ( (code == CLEAR) && block_compress ) {
  1029.             for ( code = 255; code >= 0; code-- )
  1030.                 tab_prefixof(code) = 0;
  1031.             clear_flg = 1;
  1032.             free_ent = FIRST - 1;
  1033.             if ( (code = getcode ()) == -1 )    /* O, untimely death! */
  1034.                 break;
  1035.         }
  1036.         incode = code;
  1037.         /*
  1038.          * Special case for KwKwK string.
  1039.          */
  1040.         if ( code >= free_ent ) {
  1041.             *stackp++ = finchar;
  1042.             code = oldcode;
  1043.         }
  1044.  
  1045.         /*
  1046.          * Generate output characters in reverse order
  1047.          */
  1048. #ifdef SIGNED_COMPARE_SLOW
  1049.         while ( ((unsigned long)code) >= ((unsigned long)256) ) {
  1050. #else
  1051.         while ( code >= 256 ) {
  1052. #endif
  1053.             *stackp++ = tab_suffixof(code);
  1054.             code = tab_prefixof(code);
  1055.         }
  1056.         *stackp++ = finchar = tab_suffixof(code);
  1057.  
  1058.         /*
  1059.          * And put them out in forward order
  1060.          */
  1061.         do
  1062.             putchar ( *--stackp );
  1063.         while ( stackp > de_stack );
  1064.  
  1065.         /*
  1066.          * Generate the new entry.
  1067.          */
  1068.         if ( (code=free_ent) < maxmaxcode ) {
  1069.             tab_prefixof(code) = (unsigned short)oldcode;
  1070.             tab_suffixof(code) = finchar;
  1071.             free_ent = code+1;
  1072.         } 
  1073.         /*
  1074.          * Remember previous code.
  1075.          */
  1076.         oldcode = incode;
  1077.     }
  1078.     fflush( stdout );
  1079.     if(ferror(stdout))
  1080.         writeerr();
  1081. }
  1082.  
  1083. /*****************************************************************
  1084.  * TAG( getcode )
  1085.  *
  1086.  * Read one code from the standard input.  If EOF, return -1.
  1087.  * Inputs:
  1088.  *      stdin
  1089.  * Outputs:
  1090.  *      code or -1 is returned.
  1091.  */
  1092.  
  1093. code_int
  1094. getcode() {
  1095.     /*
  1096.      * On the VAX, it is important to have the register declarations
  1097.      * in exactly the order given, or the asm will break.
  1098.      */
  1099.     register code_int code;
  1100.     static int offset = 0, size = 0;
  1101.     static char_type buf[BITS];
  1102.     register int r_off, bits;
  1103.     register char_type *bp = buf;
  1104.  
  1105.     if ( clear_flg > 0 || offset >= size || free_ent > maxcode ) {
  1106.         /*
  1107.          * If the next entry will be too big for the current code
  1108.          * size, then we must increase the size.  This implies reading
  1109.          * a new buffer full, too.
  1110.          */
  1111.         if ( free_ent > maxcode ) {
  1112.             n_bits++;
  1113.             if ( n_bits == maxbits )
  1114.                 maxcode = maxmaxcode;   /* won't get any bigger now */
  1115.             else
  1116.                 maxcode = MAXCODE(n_bits);
  1117.         }
  1118.         if ( clear_flg > 0) {
  1119.             maxcode = MAXCODE (n_bits = INIT_BITS);
  1120.             clear_flg = 0;
  1121.         }
  1122.         size = fread( buf, 1, n_bits, stdin );
  1123.         if ( size <= 0 )
  1124.             return -1;                  /* end of file */
  1125.         offset = 0;
  1126.         /* Round size down to integral number of codes */
  1127.         size = (size << 3) - (n_bits - 1);
  1128.     }
  1129.     r_off = offset;
  1130.     bits = n_bits;
  1131. #ifdef vax
  1132.     asm( "extzv   r10,r9,(r8),r11" );
  1133. #else /* not a vax */
  1134.         /*
  1135.          * Get to the first byte.
  1136.          */
  1137.         bp += (r_off >> 3);
  1138.         r_off &= 7;
  1139.         /* Get first part (low order bits) */
  1140. #ifdef NO_UCHAR
  1141.         code = ((*bp++ >> r_off) & rmask[8 - r_off]) & 0xff;
  1142. #else
  1143.         code = (*bp++ >> r_off);
  1144. #endif /* NO_UCHAR */
  1145.         bits -= (8 - r_off);
  1146.         r_off = 8 - r_off;              /* now, offset into code word */
  1147.         /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
  1148.         if ( bits >= 8 ) {
  1149. #ifdef NO_UCHAR
  1150.             code |= (*bp++ & 0xff) << r_off;
  1151. #else
  1152.             code |= *bp++ << r_off;
  1153. #endif /* NO_UCHAR */
  1154.             r_off += 8;
  1155.             bits -= 8;
  1156.         }
  1157.         /* high order bits. */
  1158.         code |= (*bp & rmask[bits]) << r_off;
  1159. #endif /* vax */
  1160.     offset += n_bits;
  1161.  
  1162.     return code;
  1163. }
  1164.  
  1165. char *
  1166. rindex(s, c)            /* For those who don't have it in libc.a */
  1167. register char *s, c;
  1168. {
  1169.         char *p;
  1170.         for (p = NULL; *s; s++)
  1171.             if (*s == c)
  1172.                 p = s;
  1173.         return(p);
  1174. }
  1175.  
  1176. #ifdef DEBUG
  1177. printcodes()
  1178. {
  1179.     /*
  1180.      * Just print out codes from input file.  For debugging.
  1181.      */
  1182.     code_int code;
  1183.     int col = 0, bits;
  1184.  
  1185.     bits = n_bits = INIT_BITS;
  1186.     maxcode = MAXCODE(n_bits);
  1187.     free_ent = ((block_compress) ? FIRST : 256 );
  1188.     while ( ( code = getcode() ) >= 0 ) {
  1189.         if ( (code == CLEAR) && block_compress ) {
  1190.             free_ent = FIRST - 1;
  1191.             clear_flg = 1;
  1192.         }
  1193.         else if ( free_ent < maxmaxcode )
  1194.             free_ent++;
  1195.         if ( bits != n_bits ) {
  1196.             fprintf(stderr, "\nChange to %d bits\n", n_bits );
  1197.             bits = n_bits;
  1198.             col = 0;
  1199.         }
  1200.         fprintf(stderr, "%5d%c", code, (col+=6) >= 74 ? (col = 0, '\n') : ' ' );
  1201.     }
  1202.     putc( '\n', stderr );
  1203.     exit( 0 );
  1204. }
  1205.  
  1206. code_int sorttab[1<<BITS];      /* sorted pointers into htab */
  1207.  
  1208. dump_tab()      /* dump string table */
  1209. {
  1210.     register int i, first;
  1211.     register ent;
  1212. #define STACK_SIZE      15000
  1213.     int stack_top = STACK_SIZE;
  1214.     register c;
  1215.  
  1216.     if(do_decomp == 0) {        /* compressing */
  1217.         register int flag = 1;
  1218.  
  1219.         for(i=0; i<hsize; i++) {        /* build sort pointers */
  1220.                 if((long)htabof(i) >= 0) {
  1221.                         sorttab[codetabof(i)] = i;
  1222.                 }
  1223.         }
  1224.         first = block_compress ? FIRST : 256;
  1225.         for(i = first; i < free_ent; i++) {
  1226.                 fprintf(stderr, "%5d: \"", i);
  1227.                 de_stack[--stack_top] = '\n';
  1228.                 de_stack[--stack_top] = '"';
  1229.                 stack_top = in_stack((htabof(sorttab[i])>>maxbits)&0xff, 
  1230.                                      stack_top);
  1231.                 for(ent=htabof(sorttab[i]) & ((1<<maxbits)-1);
  1232.                     ent > 256;
  1233.                     ent=htabof(sorttab[ent]) & ((1<<maxbits)-1)) {
  1234.                         stack_top = in_stack(htabof(sorttab[ent]) >> maxbits,
  1235.                                                 stack_top);
  1236.                 }
  1237.                 stack_top = in_stack(ent, stack_top);
  1238.                 fwrite( &de_stack[stack_top], 1, STACK_SIZE-stack_top, stderr);
  1239.                 stack_top = STACK_SIZE;
  1240.         }
  1241.    } else if(!debug) {  /* decompressing */
  1242.  
  1243.        for ( i = 0; i < free_ent; i++ ) {
  1244.            ent = i;
  1245.            c = tab_suffixof(ent);
  1246.            if ( isascii(c) && isprint(c) )
  1247.                fprintf( stderr, "%5d: %5d/'%c'  \"",
  1248.                            ent, tab_prefixof(ent), c );
  1249.            else
  1250.                fprintf( stderr, "%5d: %5d/\\%03o \"",
  1251.                            ent, tab_prefixof(ent), c );
  1252.            de_stack[--stack_top] = '\n';
  1253.            de_stack[--stack_top] = '"';
  1254.            for ( ; ent != NULL;
  1255.                    ent = (ent >= FIRST ? tab_prefixof(ent) : NULL) ) {
  1256.                stack_top = in_stack(tab_suffixof(ent), stack_top);
  1257.            }
  1258.            fwrite( &de_stack[stack_top], 1, STACK_SIZE - stack_top, stderr );
  1259.            stack_top = STACK_SIZE;
  1260.        }
  1261.     }
  1262. }
  1263.  
  1264. int
  1265. in_stack(c, stack_top)
  1266.         register c, stack_top;
  1267. {
  1268.         if ( (isascii(c) && isprint(c) && c != '\\') || c == ' ' ) {
  1269.             de_stack[--stack_top] = c;
  1270.         } else {
  1271.             switch( c ) {
  1272.             case '\n': de_stack[--stack_top] = 'n'; break;
  1273.             case '\t': de_stack[--stack_top] = 't'; break;
  1274.             case '\b': de_stack[--stack_top] = 'b'; break;
  1275.             case '\f': de_stack[--stack_top] = 'f'; break;
  1276.             case '\r': de_stack[--stack_top] = 'r'; break;
  1277.             case '\\': de_stack[--stack_top] = '\\'; break;
  1278.             default:
  1279.                 de_stack[--stack_top] = '0' + c % 8;
  1280.                 de_stack[--stack_top] = '0' + (c / 8) % 8;
  1281.                 de_stack[--stack_top] = '0' + c / 64;
  1282.                 break;
  1283.             }
  1284.             de_stack[--stack_top] = '\\';
  1285.         }
  1286.         return stack_top;
  1287. }
  1288. #endif /* DEBUG */
  1289.  
  1290. writeerr()
  1291. {
  1292. #ifdef __riscos
  1293.     fclose(stdout);
  1294.     fprintf(stderr, "write error on %s\n", ofname);
  1295. #else
  1296.     perror ( ofname );
  1297. #endif
  1298.     unlink ( ofname );
  1299.     exit ( 1 );
  1300. }
  1301.  
  1302. copystat(ifname, ofname)
  1303. char *ifname, *ofname;
  1304. {
  1305.     struct stat statbuf;
  1306.     int mode;
  1307. #ifndef __riscos
  1308.     time_t timep[2];
  1309. #endif
  1310.  
  1311.     fclose(stdout);
  1312.     if (stat(ifname, &statbuf)) {               /* Get stat on input file */
  1313. #ifdef __riscos
  1314.         fprintf(stderr, "unable to stat %s\n", ifname);
  1315. #else
  1316.         perror(ifname);
  1317. #endif
  1318.         return;
  1319.     }
  1320. #ifdef __riscos
  1321.     if (statbuf.st_type != 1) {
  1322. #else
  1323.     if ((statbuf.st_mode & S_IFMT/*0170000*/) != S_IFREG/*0100000*/) {
  1324. #endif
  1325.         if(quiet)
  1326.                 fprintf(stderr, "%s: ", ifname);
  1327.         fprintf(stderr, " -- not a regular file: unchanged");
  1328.         exit_stat = 1;
  1329. #ifndef __riscos
  1330.     } else if (statbuf.st_nlink > 1) {
  1331.         if(quiet)
  1332.                 fprintf(stderr, "%s: ", ifname);
  1333.         fprintf(stderr, " -- has %d other links: unchanged",
  1334.                 statbuf.st_nlink - 1);
  1335.         exit_stat = 1;
  1336. #endif
  1337.     } else if (exit_stat == 2 && (!force)) { /* No compression: remove file.Z */
  1338.         if(!quiet)
  1339.                 fprintf(stderr, " -- file unchanged");
  1340.     } else {                    /* ***** Successful Compression ***** */
  1341.         exit_stat = 0;
  1342. #ifdef __riscos
  1343.         wstat(ofname, &statbuf);
  1344. #else
  1345.         mode = statbuf.st_mode & 07777;
  1346.         if (chmod(ofname, mode))                /* Copy modes */
  1347.             perror(ofname);
  1348.         chown(ofname, statbuf.st_uid, statbuf.st_gid);  /* Copy ownership */
  1349.         timep[0] = statbuf.st_atime;
  1350.         timep[1] = statbuf.st_mtime;
  1351.         utime(ofname, timep);   /* Update last accessed and modified times */
  1352. #endif
  1353. #ifdef __riscos
  1354.         fclose(stdin);
  1355. #endif
  1356.         if (unlink(ifname))     /* Remove input file */
  1357. #ifdef __riscos
  1358.             fprintf(stderr,"\nUnable to remove %s\n",ifname);
  1359. #else
  1360.             perror(ifname);
  1361. #endif
  1362.         if(!quiet)
  1363.                 fprintf(stderr, " -- replaced with %s", ofname);
  1364.         return;         /* Successful return */
  1365.     }
  1366.  
  1367.     /* Unsuccessful return -- one of the tests failed */
  1368. #ifdef __riscos
  1369.     fclose(stdout);
  1370. #endif
  1371.     if (unlink(ofname))
  1372. #ifdef __riscos
  1373.         fprintf(stderr,"\nUnable to remove %s\n",ofname);
  1374. #else
  1375.         perror(ofname);
  1376. #endif
  1377. }
  1378. /*
  1379.  * This routine returns 1 if we are running in the foreground and stderr
  1380.  * is a tty.
  1381.  */
  1382. foreground()
  1383. {
  1384. #ifdef __riscos
  1385.         return 1;
  1386. #else
  1387.         if(bgnd_flag) { /* background? */
  1388.                 return(0);
  1389.         } else {                        /* foreground */
  1390.                 if(isatty(2)) {         /* and stderr is a tty */
  1391.                         return(1);
  1392.                 } else {
  1393.                         return(0);
  1394.                 }
  1395.         }
  1396. #endif
  1397. }
  1398.  
  1399. onintr ( )
  1400. {
  1401. #ifdef __riscos
  1402.     fclose(stdout);
  1403. #endif
  1404.     unlink ( ofname );
  1405.     exit ( 1 );
  1406. }
  1407.  
  1408. oops ( )        /* wild pointer -- assume bad input */
  1409. {
  1410.     if ( do_decomp == 1 ) 
  1411.         fprintf ( stderr, "uncompress: corrupt input\n" );
  1412. #ifdef __riscos
  1413.     fclose(stdout);
  1414. #endif
  1415.     unlink ( ofname );
  1416.     exit ( 1 );
  1417. }
  1418.  
  1419. cl_block ()             /* table clear for block compress */
  1420. {
  1421.     register long int rat;
  1422.  
  1423.     checkpoint = in_count + CHECK_GAP;
  1424. #ifdef DEBUG
  1425.         if ( debug ) {
  1426.                 fprintf ( stderr, "count: %ld, ratio: ", in_count );
  1427.                 prratio ( stderr, in_count, bytes_out );
  1428.                 fprintf ( stderr, "\n");
  1429.         }
  1430. #endif /* DEBUG */
  1431.  
  1432.     if(in_count > 0x007fffff) { /* shift will overflow */
  1433.         rat = bytes_out >> 8;
  1434.         if(rat == 0) {          /* Don't divide by zero */
  1435.             rat = 0x7fffffff;
  1436.         } else {
  1437.             rat = in_count / rat;
  1438.         }
  1439.     } else {
  1440.         rat = (in_count << 8) / bytes_out;      /* 8 fractional bits */
  1441.     }
  1442.     if ( rat > ratio ) {
  1443.         ratio = rat;
  1444.     } else {
  1445.         ratio = 0;
  1446. #ifdef DEBUG
  1447.         if(verbose)
  1448.                 dump_tab();     /* dump string table */
  1449. #endif
  1450.         cl_hash ( (count_int) hsize );
  1451.         free_ent = FIRST;
  1452.         clear_flg = 1;
  1453.         output ( (code_int) CLEAR );
  1454. #ifdef DEBUG
  1455.         if(debug)
  1456.                 fprintf ( stderr, "clear\n" );
  1457. #endif /* DEBUG */
  1458.     }
  1459. }
  1460.  
  1461. cl_hash(hsize)          /* reset code table */
  1462.         register count_int hsize;
  1463. {
  1464. #ifndef XENIX_16        /* Normal machine */
  1465.         register count_int *htab_p = htab+hsize;
  1466. #else
  1467.         register j;
  1468.         register long k = hsize;
  1469.         register count_int *htab_p;
  1470. #endif
  1471.         register long i;
  1472.         register long m1 = -1;
  1473.  
  1474. #ifdef XENIX_16
  1475.     for(j=0; j<=8 && k>=0; j++,k-=8192) {
  1476.         i = 8192;
  1477.         if(k < 8192) {
  1478.                 i = k;
  1479.         }
  1480.         htab_p = &(htab[j][i]);
  1481.         i -= 16;
  1482.         if(i > 0) {
  1483. #else
  1484.         i = hsize - 16;
  1485. #endif
  1486.         do {                            /* might use Sys V memset(3) here */
  1487.                 *(htab_p-16) = m1;
  1488.                 *(htab_p-15) = m1;
  1489.                 *(htab_p-14) = m1;
  1490.                 *(htab_p-13) = m1;
  1491.                 *(htab_p-12) = m1;
  1492.                 *(htab_p-11) = m1;
  1493.                 *(htab_p-10) = m1;
  1494.                 *(htab_p-9) = m1;
  1495.                 *(htab_p-8) = m1;
  1496.                 *(htab_p-7) = m1;
  1497.                 *(htab_p-6) = m1;
  1498.                 *(htab_p-5) = m1;
  1499.                 *(htab_p-4) = m1;
  1500.                 *(htab_p-3) = m1;
  1501.                 *(htab_p-2) = m1;
  1502.                 *(htab_p-1) = m1;
  1503.                 htab_p -= 16;
  1504.         } while ((i -= 16) >= 0);
  1505. #ifdef XENIX_16
  1506.         }
  1507.     }
  1508. #endif
  1509.         for ( i += 16; i > 0; i-- )
  1510.                 *--htab_p = m1;
  1511. }
  1512.  
  1513. prratio(stream, num, den)
  1514. FILE *stream;
  1515. long int num, den;
  1516. {
  1517.         register int q;                 /* Doesn't need to be long */
  1518.  
  1519.         if(num > 214748L) {             /* 2147483647/10000 */
  1520.                 q = num / (den / 10000L);
  1521.         } else {
  1522.                 q = 10000L * num / den;         /* Long calculations, though */
  1523.         }
  1524.         if (q < 0) {
  1525.                 putc('-', stream);
  1526.                 q = -q;
  1527.         }
  1528.         fprintf(stream, "%d.%02d%%", q / 100, q % 100);
  1529. }
  1530.  
  1531. version()
  1532. {
  1533.         fprintf(stderr, "%s\n", rcs_ident);
  1534.         fprintf(stderr, "Options: ");
  1535. #ifdef vax
  1536.         fprintf(stderr, "vax, ");
  1537. #endif
  1538. #ifdef NO_UCHAR
  1539.         fprintf(stderr, "NO_UCHAR, ");
  1540. #endif
  1541. #ifdef SIGNED_COMPARE_SLOW
  1542.         fprintf(stderr, "SIGNED_COMPARE_SLOW, ");
  1543. #endif
  1544. #ifdef XENIX_16
  1545.         fprintf(stderr, "XENIX_16, ");
  1546. #endif
  1547. #ifdef COMPATIBLE
  1548.         fprintf(stderr, "COMPATIBLE, ");
  1549. #endif
  1550. #ifdef DEBUG
  1551.         fprintf(stderr, "DEBUG, ");
  1552. #endif
  1553. #ifdef BSD4_2
  1554.         fprintf(stderr, "BSD4_2, ");
  1555. #endif
  1556.         fprintf(stderr, "BITS = %d\n", BITS);
  1557. }
  1558.